package com.godyao.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.godyao.annotations.LimitAccessor;
import com.godyao.enums.ResponseCodeEnum;
import com.godyao.enums.ResultMsg;
import com.godyao.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author godyao
 * @date 2022/3/25
 */
@Component
public class LimitRateInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            final ValueOperations valueOperations = redisTemplate.opsForValue();
            final HandlerMethod hm = (HandlerMethod) handler;

            if (hm.hasMethodAnnotation(LimitAccessor.class)) {
                final LimitAccessor annotation = hm.getMethodAnnotation(LimitAccessor.class);
                final int time = annotation.time();
                final int count = annotation.count();
                final boolean login = annotation.login();
                final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (login) {
                    if (!authentication.isAuthenticated()) {
                        throw new Exception(ResponseCodeEnum.NO_AHTU.getDesc());
                        //render(response, ResponseCodeEnum.NO_AHTU);
                    }

                }
                final SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

                String key = "seckillLimit:" + request.getRequestURI() + securityUser.getUsername();
                if (!valueOperations.getOperations().hasKey(key)) {
                    valueOperations.set(key, count, time, TimeUnit.SECONDS);
                } else {
                    if ((int) valueOperations.get(key) > count) {
                        //render(response, ResponseCodeEnum.TO_MUCH);
                        throw new Exception(ResponseCodeEnum.TO_MUCH.getDesc());
                    } else {
                        valueOperations.increment(key);
                    }

                }

            }
        }
        return true;
    }

    //public void render(HttpServletResponse response, ResponseCodeEnum responseCodeEnum) throws IOException {
    //    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    //    final ResultMsg resultMsg = new ResultMsg(responseCodeEnum, null);
    //    final PrintWriter writer = response.getWriter();
    //    writer.write(new ObjectMapper().writeValueAsString(resultMsg));
    //    writer.flush();
    //    writer.close();
    //}
}
